package com.sunday.common.easy.excel.handler;

import com.sunday.common.core.remoting.rest.response.RestExceptionResponse;
import com.sunday.common.core.remoting.rest.response.RestResponse;
import com.sunday.common.easy.excel.utils.DownloadUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;

import java.io.IOException;

/**
 * easy execl 异常特殊处理-辅助工具
 *
 * @author zsy
 * @since 2022/12/2
 */
@Slf4j
public class EasyExcelHandler {

    public static void download(HttpServletResponse response, String fileName, ExecuteHandler handler) throws IOException {
        download(response, fileName, handler, null);
    }


    public static void download(HttpServletResponse response, String fileName, ExecuteHandler handler, @Nullable RestResponse.ShowTypeEnum showTypeEnum) throws IOException {
        try {
            assert handler != null : "handler must not be null";
            DownloadUtils.setFileName(response, fileName);
            handler.doWith(response);
        } catch (Throwable e) {
            log.error(e.toString(), e);
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            RestResponse restResponse = RestExceptionResponse.returnResponse(e, showTypeEnum == null ? RestResponse.ShowTypeEnum.ERROR_MESSAGE : showTypeEnum);
            response.getWriter().println(restResponse);
        }
    }

    /**
     * @Description: 执行处理程序
     */
    @FunctionalInterface
    public interface ExecuteHandler {
        void doWith(HttpServletResponse response) throws Exception;
    }

}
